<template>
  <el-dialog
    v-dialogDrag
    v-loading="loading"
    class="Dialog"
    title="用户分配"
    :visible.sync="dialogVisible"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <el-header class="header" height="40px">
      <el-form :inline="true" :model="queryData" class="form">
        <el-form-item class="formItem" label="用户查询">
          <el-input v-model="queryData.name" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </el-header>
    <el-main class="body" align="center">
      <el-table
        v-if="isEmpty===false"
        ref="userTable"
        :data="tableData"
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}"
        height="400px"
        :row-key="getRowKeys"
        :border="true"
        style="width:100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column fixed type="selection" width="50" :reserve-selection="true" />
        <el-table-column prop="code" label="用户工号" width="126" />
        <el-table-column prop="name" label="用户名" width="100" />
        <el-table-column prop="company.name" label="公司" width="80" />
        <el-table-column prop="department.name" label="部门" />
        <!-- <el-table-column
          prop="status"
          label="标签"
        /> -->
      </el-table>
      <el-empty v-if="isEmpty===true" description="暂无数据" />
      <div class="block" align="center">
        <el-pagination
          :current-page="paginationInfo.pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="paginationInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paginationInfo.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-main>
    <el-footer height="40px" align="right">
      <el-button @click="closed">取 消</el-button>
      <el-button type="primary" @click="assignUser">确 定</el-button>
    </el-footer>
  </el-dialog>

</template>

<script>
import { getUserListAPI, assignUserAPI } from '@/api/rolesAPI'
export default {
  props: {
    rolesId: {
      type: Array,
      default: () => { return [] }
    }
  },
  data() {
    return {
      defaultQueryData: {
        pageNum: 1,
        pageSize: 10
      },
      queryData: {
        pageNum: 1,
        pageSize: 15,
        name: ''
      },
      dialogVisible: false,
      tableData: [],
      paginationInfo: {},
      multipleSelection: [],
      loading: false,
      isEmpty: false
    }
  },
  created() {

  },
  mounted() {
    this.inintUI()
  },
  methods: {
    onShow() {
      this.inintUI()
      this.dialogVisible = true
      this.getUserList(this.defaultQueryData)
    },
    getRowKeys(row) {
      return row.id // id 能标识唯一的 table 行;
    },
    /**
     * 多选处理
     * @param {*} val
     */
    handleSelectionChange(val) {
      // console.log(val)
      this.multipleSelection = []
      // 假设取出 id 字段
      val.forEach(item => {
        const newObject = item.id
        // 判断数组中是否包含这个 id
        if (this.multipleSelection.indexOf(newObject) === -1) {
          this.multipleSelection.push(newObject)
        }
      })
    },
    /**
     * 界面初始化
     */
    inintUI() {
      this.tableData = []
      this.queryData = {
        pageNum: 1,
        pageSize: 15
      }
    },
    /**
    *向后端发起请求，获取页面数据
    */
    getUserList(queryData) {
      // 获取数据动作
      this.loading = true
      this.isEmpty = false
      getUserListAPI(queryData)
        .then(
          (compos) => {
            if (compos) {
              this.tableData = compos.data
              const { total, pageNum, pageSize, pages } = compos
              this.paginationInfo = { total, pageNum, pageSize, pages }
              this.paginationInfo.total = parseInt(this.paginationInfo.total)
            } else {
              this.isEmpty = true
            }
            this.loading = false
          }
        ).catch((error) => {
          this.$message({
            message: '获取用户列表失败',
            type: 'error',
            duration: 5000
          })
          this.loading = false
          console.log(error)
        })
    },
    /**
     * 查询按钮提交功能实现
     */
    searchSubmit() {
      this.getUserList(this.queryData)
    },
    /**
     * 页面条数修改处理
     * @param {*} val
     */
    handleSizeChange(val) {
      this.paginationInfo.pageSize = val
      /**
       * 页面尺寸变化时，初始化页码为一
       */
      this.paginationInfo.pageNum = 1
      this.queryData.pageNum = 1
      /**
       * 根据新size重新发起请求
       */
      this.queryData.pageSize = val
      this.getUserList(this.queryData)
      console.log(`每页 ${val} 条`)
    },
    /**
     * 页面跳转处理
     * @param {*} val
     */
    handleCurrentChange(val) {
      this.paginationInfo.pageNum = val
      /**
       * 根据新页码重新发起请求
       */
      console.log(`当前页: ${val}`)
      this.queryData.pageNum = val
      this.getUserList(this.queryData)
    },
    /**
     * 表单提交函数
     */
    assignUser() {
      /**
       * 选择用户为空时，提交报错
       */
      if (this.multipleSelection.length === 0) {
        this.$message.error('请至少选择一个用户')
      } else {
        const assignUserData = {}
        assignUserData.roleIds = []
        assignUserData.userIds = this.multipleSelection
        for (const item of this.rolesId) { assignUserData.roleIds.push(item.id) }
        this.loading = true
        assignUserAPI(assignUserData)
          .then((res) => {
            if (res) {
              this.$message({
                message: '用户分配成功',
                type: 'success',
                duration: 5000
              })
              // 清空多选框
              this.$refs.userTable.clearSelection()
              // 触发分配结束事件，父组件刷新

              this.$emit('assignUserEnd')
              this.loading = false
              this.closed()
            } else {
              this.$message({
                message: '用户分配失败',
                type: 'error',
                duration: 5000
              })
              this.loading = false
            }
          })
          .catch((error) => {
            this.$message({
              message: '用户分配失败',
              type: 'error',
              duration: 5000
            })
            this.loading = false
            console.log(error)
          })
      }
    },
    closed() {
      this.tableData = []
      this.$refs.userTable.clearSelection()
      this.dialogVisible = false
    }
  }
}
</script>
<style scoped>
::v-deep .header{
padding-bottom: 0px;
margin-bottom: 0;
}
::v-deep .form{
  height: 20px;
}

::v-deep .Dialog{
  height: 620px;
  padding-top: 10px;
}
</style>
<style>
.Dialog{
  .el-table__cell{
    padding: 5px 0;
  }
  &.el-dialog__body{
    padding-top: 10px;
  }
}
</style>
